package com.codeant.bikeindicatorapplication;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.PowerManager;

public class BackGroundService extends Service {
    Notification notification;
    private Context mContext;
    private static Thread uploadGpsThread;
    private MediaPlayer bgmediaPlayer;
    private boolean isrun = true;

    PowerManager pm = null;
    PowerManager.WakeLock wakeLock = null;

    /*
    后台保活分析，不好实现
    https://www.cnblogs.com/xiaxveliang/p/15478580.html
    */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext = this;

        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
        wakeLock.acquire();

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        //1.通知栏占用，不清楚的看官网或者音乐类APP的效果
        notification = new Notification.Builder(mContext)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .setTicker(getResources().getString(R.string.app_name))
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText("正在后台运行")
                .setOngoing(true)
                .setPriority(Notification.PRIORITY_LOW)
                .setSound(null)
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .build();

        /*使用startForeground,如果id为0，那么notification将不会显示*/
        startForeground(2479, buildNotification());
        ////2.开启线程（或者需要定时操作的事情）
        //if(uploadGpsThread == null){
        //    uploadGpsThread = new Thread(new Runnable() {
        //        @Override
        //        public void run() {
        //            //这里用死循环就是模拟一直执行的操作
        //            while (isrun){
        //
        //                //你需要执行的任务
        //                //doSomething();
        //
        //                try {
        //                    Thread.sleep(10000L);
        //                } catch (InterruptedException e) {
        //                    e.printStackTrace();
        //                }
        //            }
        //        }
        //    });
        //}
        //3.最关键，也是最投机的动作，没办法要骗过CPU
        //这就是播放音乐类APP不被杀的做法，自己找个无声MP3放进来循环播放
        //slient自己百度找一个无声的mp3即可
        if(bgmediaPlayer == null){
            bgmediaPlayer = MediaPlayer.create(this,R.raw.silent);
            bgmediaPlayer.setLooping(true);
            bgmediaPlayer.start();
        }

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        isrun = false;
        stopForeground(true);
        if (bgmediaPlayer != null){
            bgmediaPlayer.release();
        }
        stopSelf();
        if (wakeLock != null){
            wakeLock.release();
        }
        super.onDestroy();
    }

    private NotificationManager notificationManager;
    private boolean isCreateChannel = false;
    @SuppressLint("NewApi")
    private Notification buildNotification() {
        Notification.Builder builder = null;
        Notification notification = null;

        if (android.os.Build.VERSION.SDK_INT >= 26) {
            if (null == notificationManager) {
                notificationManager = (NotificationManager) getSystemService(mContext.NOTIFICATION_SERVICE);
            }
            String channelId = getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        "后台服务", NotificationManager.IMPORTANCE_LOW);
                notificationChannel.enableLights(false);//是否在桌面icon右上角展示小圆点
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationChannel.setSound(null, null);//静音
                notificationChannel.setVibrationPattern(new long[]{0});//免振动
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        builder.setSmallIcon(R.drawable.app_logo)
                .setColor(getResources().getColor(R.color.transparent))
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText("正在后台运行")
                .setSound(null)
                .setWhen(System.currentTimeMillis());
        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }
}